package com.tju.resource.oauth.controller.tb;

import com.tju.resource.annotation.Log;
import com.tju.resource.common.ServiceException;
import com.tju.resource.model.TbMaterial;
import com.tju.resource.business.tb_material.TbMaterialService;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.enum_utils.FunctionType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
public class TbMaterialController {

    private static final String prefix = "matl";

    @Autowired
    TbMaterialService service;
    @Log(type= FunctionType.List)
    @PostMapping(prefix + "/getAll")
    @PreAuthorize("hasAnyAuthority('sys:tool:matl:list','sys:warehouse:fpStore:list','sys:warehouse:spStore:list')")
    public Result<Object> getAll(@RequestBody Map<String, String> param) {
        return service.getAll(param);
    }

    @PostMapping(prefix + "/byName")
    @PreAuthorize("hasAuthority('sys:tool:matl:list')")
    public Result<Object> byName(@RequestBody Map<String, String> params) {
        return service.byName(params);
    }

    @PostMapping(prefix + "/add")
    @PreAuthorize("hasAuthority('sys:tool:matl:add')")
    @Log(type= FunctionType.Add)
    public Result<Object> add(@Valid @RequestBody TbMaterial material, BindingResult result) {
        try {
            if(result.hasErrors()){
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
            }
            return service.add(material);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    @Log(type= FunctionType.Modify)
    @PostMapping(prefix + "/upd")
    @PreAuthorize("hasAnyAuthority('sys:tool:matl:edit','sys:warehouse:fpStore:edit','sys:warehouse:spStore:edit')")
    public Result<Object> upd(@Valid @RequestBody TbMaterial material,BindingResult result) {
        try {
            if(result.hasErrors()){
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
            }
            TbMaterial matl = service.byId(material.getId());
            int updRes;

            if (null != matl) {
                matl.setSid(material.getSid());

                if (!StringUtils.equals(material.getMatlNumber(), matl.getMatlNumber())) {
                    if (null == service.byNo(material.getMatlNumber())) {
                        updRes = service.upd(material);
                    } else {
                        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "物料编号不可重复!");
                    }
                } else {
                    updRes = service.upd(material);
                }
                if (updRes > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, "更新物料完成!");
                } else {
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR, "更新失败!");
                }
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "对应物料不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }
    @Log(type= FunctionType.Modify)
    @PostMapping(prefix + "/updAll")
    @PreAuthorize("hasAnyAuthority('sys:tool:matl:edit','sys:warehouse:fpStore:edit','sys:warehouse:spStore:edit')")
    public Result<Object> updAll(@RequestBody List<TbMaterial> material) {
        material.forEach(service::upd);
        return ResultUtil.success(ResultEnum.SUCCESS, "修改完成!");
    }
    @Log(type= FunctionType.Delete)
    @PostMapping(prefix + "/del")
    @PreAuthorize("hasAuthority('sys:tool:matl:delete')")
    public Result<Object> del(@RequestBody Map<String, String> params) {
        TbMaterial material = service.byId(Long.parseLong(params.get("id")));

        if (null != material) {
            int delRes = service.del(material.getId());

            if (delRes > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, "物料删除成功!");
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "删除失败!");
            }
        } else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "对应物料不存在!");
        }
    }

    @PostMapping(prefix + "/byOrderNumber")
    @PreAuthorize("hasAuthority('sys:tool:matl:list')")
    public Result<Object> byOrderNumber(@RequestBody Map<String, String> params) {
        return service.byOrderNumber(params);
    }

    @PostMapping(prefix + "/byOrderMatlNumber")
    @PreAuthorize("hasAuthority('sys:tool:matl:list')")
    public Result<Object> byOrderMatlNumber(@RequestBody Map<String, String> params) {
        return service.byOrderMatlNumber(params);
    }

    /**
     * 添加物料下面的耗材
     *
     * @param material 物料下面的耗材
     * @return 结果
     */
    @PostMapping(prefix + "/addMatlConsumables")
    @PreAuthorize("hasAuthority('sys:tool:matl:add')")
    @Log(type= FunctionType.MaterialAddConsumables)
    public Result<Object> addMatlConsumables(@RequestBody TbMaterial material) {
        return service.addMatlConsumables(material);
    }

    /**
     * 添加物料下面的原料
     *
     * @param material 物料下面的原料
     * @return 结果
     */
    @PostMapping(prefix + "/addMatlRmMatl")
    @PreAuthorize("hasAuthority('sys:tool:matl:add')")
    @Log(type= FunctionType.MaterialRawMatl)
    public Result<Object> addMatlRmMatl(@RequestBody TbMaterial material) {
        return service.addMatlRmMatl(material);
    }
}
